'''
Desc: 通过接入号查询宽带账号或者其他的业务账号
Author: 马大胖
Mail: mazhenjun.lk.xx@gmail.com
Date: 2024-08-16 16:21:21




新一代登录之后, 拿到的 Cookie
SL_G_WPT_TO
SL_GWPT_Show_Hide_tmp
SL_wptGlobTipTmp
_AIOPS_SESSION_
LOCALE

示例:
SL_G_WPT_TO=zh; SL_GWPT_Show_Hide_tmp=1; SL_wptGlobTipTmp=1; _AIOPS_SESSION_=eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJwYXNzd29yZENoZWNrU3RhdHVzIjp0cnVlLCJwYXNzd29yZENoZWNrTXNnIjoiIiwib3JnTmFtZSI6IuS6uuWRmOiZmuaLn-mDqOmXqCIsInVzZXJfbmFtZSI6IlcxNTg3MDU5IiwidXNlcklkIjoxMTY1Mywib3JnSWQiOjcyLCJjbGllbnRfaWQiOiJpb2RDbGllbnQiLCJyb2xlSWRzIjpbMTQxMjNdLCJyZWdpb25JZCI6MjIwMDUsInNjb3BlIjpbIndlYmFwcCJdLCJzdGFmZk5hbWUiOiLliJjpsrIiLCJleHAiOjE3MjQzMjEyNTUsImp0aSI6ImUxOGJiNjFlLTY1NDItNGJjNy1iMjBhLTliYmYzNjgwZDdmYyJ9.NyhfBHG9tTE9mm8GApedqdR-upl1N1xsJrqpN0AqTWPYlxIEXRPQvqP3S6RxGEUz7uM_eL10Y9C2M8_zg4Nu7XANufcAGthLVA0aT7rszFssHPG1U1qXxfrgZT7j_kjtlv2sDbBvVVObMW2QJR9qighVqy6Y7Phc17KT2YcBPvz0EUoER5vKv6rBUKzyEMnkxqimeyGUOUavs3C5Yq37DJfR2onytO7XKT6AI5hyISSQjS5MQ_iSfEASeMkoAj9vn1gXqG4RM_wExYwViNLuaefffL85A2eAddtTiLfRlxaG6BMXV8HY1Y_AhgNTpCCVIS-vefXaJl12H7tkTu91Pg@eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJwYXNzd29yZENoZWNrU3RhdHVzIjp0cnVlLCJwYXNzd29yZENoZWNrTXNnIjoiIiwib3JnTmFtZSI6IuS6uuWRmOiZmuaLn-mDqOmXqCIsInVzZXJfbmFtZSI6IlcxNTg3MDU5IiwidXNlcklkIjoxMTY1Mywib3JnSWQiOjcyLCJjbGllbnRfaWQiOiJpb2RDbGllbnQiLCJyb2xlSWRzIjpbMTQxMjNdLCJyZWdpb25JZCI6MjIwMDUsInNjb3BlIjpbIndlYmFwcCJdLCJhdGkiOiJlMThiYjYxZS02NTQyLTRiYzctYjIwYS05YmJmMzY4MGQ3ZmMiLCJzdGFmZk5hbWUiOiLliJjpsrIiLCJleHAiOjE3MjQzMjMwNTUsImp0aSI6IjRlNDMwMGNlLWQzODktNDM0Yy1hMzA5LTNiM2NjNWU5MzNkNSJ9.B6xIrVjXsIM_JkH7K2LCELn7Y26rkt5cmHGECLZY3deOoP0Q_3xyNtOE9Ls0oIsOGbBnsjQtRftndDTPAgFy5XfqgLfgj71jFhcfO56DnTZqG9WWzFosucCHvDdpKNvSfbAb2yORYreyzhi0gDyfMqjCU-BQ4WWOXQmGdlWHMnJFIFKrQlCqFHw9hqzVILSWkgqeGLPJNX9DgbwBjfjP4avMhR8rk55uqVZa7h2zGv8h7-YLVaC7AgZBuZ-QzJXIIK0nlU9BRxEBRz26mYtjFaF3ixEu-llkG4G_r1o6mEAkTORnzPT395-_rUjtk3NgB2uFZtuSxxy06iABn-q3HQ@@-1@true; LOCALE=zh-CN



'''

import tkinter as tk
from tkinter import scrolledtext
from tkinter.messagebox import *
import requests
import logging
# from selenium import webdriver
from tkinter import ttk
from selenium import webdriver

# 根据 接入号 查询新一代施工调度中的待办箱列表
find_todo_box_url = "http://136.64.71.234:30121/aiops/api/v1/flow/tj/constructionWorkTable/getGzConstructionInfo"
# 根据 flowId 查询接入号对应的 formId 和 pId
find_formIdAndPid_url = "http://136.64.71.234:30121/aiops/api/v1/form/getFlowForm"
# 根据 formId 和 pId 查询业务列表
find_broadband_info_url = "http://136.64.71.234:30121/aiops/api/v1/form/getFormData"

# 设置全局代理代理
proxies = {
    "http": "http://136.64.71.234:30121",
    "https": "http://136.64.71.234:30121"
}


def step_one_get_base_data(access_code, headers):
    global result_param
    payload = {
        "accessNo": "",
        "type": "B",
        "page": 0,
        "pageSize": 12
    }
    payload['accessNo'] = access_code

    try:
        response = requests.post(find_todo_box_url, headers=headers, json=payload, proxies=proxies)

        if response.status_code == 200:
            re = response.json()
            if re and "content" in re:
                for key in re.get("content", []):
                    result_param = {
                        "flow_id": key.get("flow_id"),
                        "access_no": key.get("access_no"),
                        "address": key.get("address"),
                        "url": key.get("url")
                    }
            return result_param
        else:
            logging.error(
                f"获取 接入号: {access_code} 的基础数据失败, 状态码: {response.status_code}, 响应内容: {response.text}")
            return None
    except requests.RequestException as e:
        logging.error(f"请求失败: {e}")
        return None


def getFormIdAndPid(result_param, headers):
    params = {'flowId': result_param.get("flow_id")}
    try:
        step_two_result = requests.get(find_formIdAndPid_url, headers=headers, params=params, proxies=proxies)

        if step_two_result.status_code == 200:
            step_two_result = step_two_result.json()
            if step_two_result:
                table_root = step_two_result["table"]
                for table in table_root:
                    for t_tmp in table.get("field", {}):
                        if t_tmp.get("fieldName") == "REQUEST_ID":
                            result_param["pId"] = t_tmp.get("value")
                        if t_tmp.get("fieldName") == "product_list_tab":
                            a = t_tmp.get("value")
                            result_param["formId"] = a.get("formId")
            return result_param
        else:
            logging.error(
                f"获取 接入号: {step_two_result.get('access_no')} 的 Form-Pid 数据失败, 状态码: {step_two_result.status_code}, 响应内容: {response.text}")
            return None
    except requests.RequestException as e:
        logging.error(f"请求失败: {e}")


def getBroadbandData(step_two_result, headers):
    params = {'formId': step_two_result.get("formId"), "pId": step_two_result.get("pId"), "pageNum": 0, "pageSize": 5}
    try:
        step_three_result = requests.get(find_broadband_info_url, headers=headers, params=params, proxies=proxies)
        if step_three_result.status_code == 200:
            step_three_result = step_three_result.json()
            if len(step_three_result) > 0:
                access_number = []
                data = step_three_result['data']
                for result_temp in data:
                    access_number.append(result_temp["accessNo"])
                access_number_unique = remove_duplicates(access_number)
                step_two_result["accounts"] = access_number_unique
                return step_two_result
        else:
            logging.error(f"获取 接入号: {step_two_result.get('access_no')} 的宽带详情数据失败")
            return None
    except requests.RequestException as e:
        logging.error(f"请求失败: {e}")
        return None


def remove_duplicates(arr):
    return list(set(arr))


# 获取 Cookie
def getCookie():

# TODO: 这样是可以拿到Cookie 的, 只要通过chrome打开的浏览器,去成功登录即可
    # 设置 Selenium WebDriver（以 Chrome 为例）
    driver = webdriver.Chrome()

    print("打开浏览器成功")

    # 访问登录页面
    driver.get('http://136.64.71.234:30121/aiops/loginm/sign')

    input("按 Enter 键继续...")

    # 等待页面加载，确保登录成功
    driver.implicitly_wait(5)

    # 获取当前的会话 Cookie
    cookies = driver.get_cookies()
    print(cookies)  # 打印所有的 Cookie

    # 继续访问其他页面，这些页面将自动携带当前会话的 Cookie
    # driver.get('https://example.com/protected-page')

    # 操作完毕后关闭浏览器
    driver.quit()


# GUI部分
def submit():
    # 获取接入号输入框的值
    access_codes = access_number_text.get("1.0", tk.END).strip().split(',')
    # 获取cookie输入框的值
    cookie = cookie_text.get("1.0", tk.END).strip()

    headers = {
        "Content-Type": "application/json;charset=UTF-8",
        "Cookie": cookie
    }

    index = 1
    # 修改为一个账号从头至尾查询
    for access_code in access_codes:
        result_param_1 = step_one_get_base_data(access_code.strip(), headers)
        if result_param_1:
            step_two_result = getFormIdAndPid(result_param_1, headers)
            if step_two_result:
                finalResult = getBroadbandData(step_two_result, headers)
                if finalResult:
                    # 已经拿到了一条数据的结果， 开始写入
                    # 写入日志
                    log_text.config(state="normal")  # 使日志区域可写
                    log_output1 = f"{index}. 查询接入号: {access_code} 成功\n"
                    log_text.insert(tk.END, log_output1)  # 插入日志信息
                    result_text.update()  # 强制刷新，使结果立即生效
                    log_text.config(state="disabled")  # 禁止用户编辑
                    # 写入结果
                    result_output = f"{index}. 地址: {finalResult.get('address', '无')} --- 账号列表: {finalResult.get('accounts', '无')} \n"
                    result_text.insert(tk.END, result_output)
                    result_text.update()  # 强制刷新，使结果立即生效

                    index += 1
                else:
                    log_text.config(state="normal")  # 使日志区域可写
                    output1 = f"{index}. 查询接入号: {access_code} 失败\n"
                    log_text.insert(tk.END, output1)  # 插入日志信息
                    log_text.config(state="disabled")  # 禁止用户编辑
                    result_text.update()  # 强制刷新，使结果立即生效
                    index = index + 1
                    return
            else:
                log_text.config(state="normal")  # 使日志区域可写
                output1 = f"{index}. 查询接入号: {access_code} 失败\n"
                log_text.insert(tk.END, output1)  # 插入日志信息
                log_text.config(state="disabled")  # 禁止用户编辑
                result_text.update()  # 强制刷新，使结果立即生效
                index = index + 1
                return
        else:
            log_text.config(state="normal")  # 使日志区域可写
            output1 = f"{index}. 查询接入号: {access_code} 失败\n"
            log_text.insert(tk.END, output1)  # 插入日志信息
            log_text.config(state="disabled")  # 禁止用户编辑
            result_text.update()  # 强制刷新，使结果立即生效
            index = index + 1
            return


# 创建主窗口
root = tk.Tk()
root.title("旭旭小仙女的工具箱")

# 调整窗口大小
root.geometry("1200x600")  # 设置窗口的初始尺寸

# 接入号标签和文本域
access_number_label = tk.Label(root, text="接入号(用逗号分隔):")
access_number_label.place(x=10, y=10)

access_number_text = tk.Text(root, height=5, width=50)
access_number_text.place(x=150, y=10, width=600, height=100)

# Cookie标签和文本域
cookie_label = tk.Label(root, text="Cookie:")
cookie_label.place(x=10, y=120)

cookie_text = tk.Text(root, height=5, width=50)
cookie_text.place(x=150, y=120, width=600, height=100)

# 获取Cookie按钮
getCookie_button = tk.Button(root, text="获取Cookie", command=getCookie)
getCookie_button.place(x=150, y=230, width=300, height=30)

# 提交按钮
submit_button = tk.Button(root, text="提交", command=submit)
submit_button.place(x=460, y=230, width=300, height=30)

# 日志显示区域 (左侧，不可编辑，背景灰色)
log_label = tk.Label(root, text="日志:")
log_label.place(x=10, y=270)

log_text = scrolledtext.ScrolledText(root, height=20, state="disabled", bg="lightgray", width=30)
log_text.place(x=10, y=300, width=350, height=250)

# 结果显示区域 (右侧，可编辑)
result_label = tk.Label(root, text="结果:")
result_label.place(x=170, y=270)

result_text = scrolledtext.ScrolledText(root, height=20, wrap=tk.NONE)
result_text.place(x=370, y=300, width=750, height=250)
# 设置 ttk 风格
style = ttk.Style()
style.configure("TScrollbar", gripcount=0,
                background="lightgray", darkcolor="gray", lightcolor="lightgray",
                troughcolor="gray", bordercolor="lightgray", arrowcolor="black")

# 创建一个 ttk 滚动条
h_scroll = ttk.Scrollbar(root, orient=tk.HORIZONTAL, command=result_text.xview, style="TScrollbar")
result_text.configure(xscrollcommand=h_scroll.set)
h_scroll.place(x=370, y=550, width=750)

# 启动主循环
root.mainloop()
